<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户ID同步测试</title>
    <link rel="stylesheet" href="./css/themes.css">
    <link rel="stylesheet" href="./components/app-header.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
        }
        
        .test-container {
            max-width: 900px;
            margin: 20px auto;
            padding: 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }
        
        .test-section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
        }
        
        .test-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .test-button {
            background: #1976d2;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            margin: 5px;
            font-size: 14px;
            transition: background-color 0.2s;
        }
        
        .test-button:hover {
            background: #1565c0;
        }
        
        .test-button.secondary {
            background: #757575;
        }
        
        .test-button.secondary:hover {
            background: #616161;
        }
        
        .test-button.success {
            background: #388e3c;
        }
        
        .test-button.success:hover {
            background: #2e7d32;
        }
        
        .test-button.danger {
            background: #d32f2f;
        }
        
        .test-button.danger:hover {
            background: #c62828;
        }
        
        .status-display {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            margin: 10px 0;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        
        .user-id-display {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 4px;
            padding: 12px;
            margin: 10px 0;
            font-weight: 600;
            color: #1976d2;
        }
        
        .log-output {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        
        .input-group {
            display: flex;
            gap: 10px;
            align-items: center;
            margin: 10px 0;
        }
        
        .input-group input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .status-indicator {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-indicator.online {
            background: #4caf50;
        }
        
        .status-indicator.offline {
            background: #f44336;
        }
        
        .status-indicator.pending {
            background: #ff9800;
            animation: pulse 1s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
    </style>
</head>
<body data-theme="blue">
    <!-- 头部区域 -->
    <div id="header-container"></div>
    
    <div class="test-container">
        <h1>🔧 用户ID同步功能测试</h1>
        
        <div class="test-section">
            <div class="test-title">
                <span class="status-indicator" id="sync-status"></span>
                当前用户ID状态
            </div>
            <div class="user-id-display" id="current-user-id">
                等待初始化...
            </div>
            <div class="status-display">
                <div><strong>HeaderHandlers用户ID:</strong> <span id="header-user-id">未知</span></div>
                <div><strong>AppHeader用户ID:</strong> <span id="app-header-user-id">未知</span></div>
                <div><strong>主进程用户ID:</strong> <span id="main-process-user-id">未知</span></div>
            </div>
        </div>
        
        <div class="test-section">
            <div class="test-title">🧪 功能测试</div>
            <button class="test-button" onclick="refreshUserIds()">刷新用户ID状态</button>
            <button class="test-button secondary" onclick="regenerateUserId()">重新生成用户ID</button>
            <button class="test-button success" onclick="testSessionList()">测试会话列表</button>
            <button class="test-button" onclick="checkSyncStatus()">检查同步状态</button>
        </div>
        
        <div class="test-section">
            <div class="test-title">⚙️ 自定义用户ID</div>
            <div class="input-group">
                <input type="text" id="custom-user-id" placeholder="输入自定义用户ID (例如: custom_user_123)" />
                <button class="test-button" onclick="setCustomUserId()">设置自定义ID</button>
            </div>
            <small>用户ID格式要求：5-50个字符，只能包含字母、数字、下划线和连字符</small>
        </div>
        
        <div class="test-section">
            <div class="test-title">📋 测试操作</div>
            <button class="test-button" onclick="testUserIdPersistence()">测试持久化</button>
            <button class="test-button secondary" onclick="simulateUserIdChange()">模拟ID变更</button>
            <button class="test-button danger" onclick="clearUserData()">清除用户数据</button>
            <button class="test-button" onclick="clearLog()">清空日志</button>
        </div>
        
        <div class="test-section">
            <div class="test-title">📝 测试日志</div>
            <div id="log-output" class="log-output">
等待测试开始...
            </div>
        </div>
    </div>

    <!-- 引入脚本 -->
    <script src="./api/session-api.js"></script>
    <script src="./handlers/header-handlers.js"></script>
    <script src="./components/app-header.js"></script>
    
    <script>
        let appHeader;
        let headerHandlers;
        let sessionAPI;
        
        // 初始化应用
        async function initApp() {
            try {
                log('🚀 开始初始化应用...');
                
                // 创建组件实例
                appHeader = new AppHeader();
                await appHeader.init();
                log('✅ AppHeader 初始化完成');
                
                headerHandlers = new HeaderHandlers();
                await headerHandlers.init(appHeader);
                log('✅ HeaderHandlers 初始化完成');
                
                sessionAPI = new SessionAPI();
                log('✅ SessionAPI 初始化完成');
                
                // 监听用户ID变更事件
                document.addEventListener('userIdChanged', (event) => {
                    log(`🔄 用户ID已变更: ${event.detail.userId}`);
                    refreshUserIds();
                });
                
                // 监听会话选择事件
                document.addEventListener('sessionSelected', (event) => {
                    log(`📋 会话被选中: ${event.detail.sessionId}`);
                });
                
                // 初始化状态显示
                await refreshUserIds();
                updateSyncStatus('online');
                
                log('🎉 应用初始化完成');
                
            } catch (error) {
                log(`❌ 初始化失败: ${error.message}`);
                updateSyncStatus('offline');
            }
        }
        
        // 刷新用户ID状态
        async function refreshUserIds() {
            try {
                const headerUserId = headerHandlers.getUserId();
                const appHeaderUserId = appHeader.getUserId();
                
                // 更新显示
                document.getElementById('current-user-id').textContent = headerUserId;
                document.getElementById('header-user-id').textContent = headerUserId;
                document.getElementById('app-header-user-id').textContent = appHeaderUserId;
                
                // 获取主进程用户ID
                if (window.electronAPI && window.electronAPI.getUserId) {
                    try {
                        const mainProcessUserId = await window.electronAPI.getUserId();
                        document.getElementById('main-process-user-id').textContent = mainProcessUserId || '未设置';
                    } catch (error) {
                        document.getElementById('main-process-user-id').textContent = '获取失败';
                        log(`⚠️ 获取主进程用户ID失败: ${error.message}`);
                    }
                } else {
                    document.getElementById('main-process-user-id').textContent = 'IPC不可用';
                }
                
                log('🔄 用户ID状态已刷新');
                
            } catch (error) {
                log(`❌ 刷新用户ID失败: ${error.message}`);
            }
        }
        
        // 重新生成用户ID
        function regenerateUserId() {
            try {
                const oldUserId = headerHandlers.getUserId();
                const newUserId = headerHandlers.regenerateUserId();
                log(`🔄 用户ID已重新生成: ${oldUserId} -> ${newUserId}`);
                setTimeout(refreshUserIds, 100);
            } catch (error) {
                log(`❌ 重新生成用户ID失败: ${error.message}`);
            }
        }
        
        // 设置自定义用户ID
        function setCustomUserId() {
            const customId = document.getElementById('custom-user-id').value.trim();
            if (!customId) {
                log('⚠️ 请输入自定义用户ID');
                return;
            }
            
            try {
                const oldUserId = headerHandlers.getUserId();
                headerHandlers.setCustomUserId(customId);
                log(`✅ 自定义用户ID已设置: ${oldUserId} -> ${customId}`);
                document.getElementById('custom-user-id').value = '';
                setTimeout(refreshUserIds, 100);
            } catch (error) {
                log(`❌ 设置自定义用户ID失败: ${error.message}`);
            }
        }
        
        // 测试会话列表
        async function testSessionList() {
            try {
                log('🧪 测试会话列表功能...');
                appHeader.showSessionDropdown();
                log('📋 会话列表已显示');
            } catch (error) {
                log(`❌ 测试会话列表失败: ${error.message}`);
            }
        }
        
        // 检查同步状态
        async function checkSyncStatus() {
            try {
                log('🔍 检查同步状态...');
                
                const headerUserId = headerHandlers.getUserId();
                const appHeaderUserId = appHeader.getUserId();
                
                let mainProcessUserId = null;
                if (window.electronAPI && window.electronAPI.getUserId) {
                    mainProcessUserId = await window.electronAPI.getUserId();
                }
                
                const allMatch = headerUserId === appHeaderUserId && 
                                headerUserId === mainProcessUserId;
                
                if (allMatch) {
                    log('✅ 所有组件的用户ID同步正常');
                    updateSyncStatus('online');
                } else {
                    log('⚠️ 用户ID同步不一致:');
                    log(`  HeaderHandlers: ${headerUserId}`);
                    log(`  AppHeader: ${appHeaderUserId}`);
                    log(`  MainProcess: ${mainProcessUserId}`);
                    updateSyncStatus('offline');
                }
                
            } catch (error) {
                log(`❌ 检查同步状态失败: ${error.message}`);
                updateSyncStatus('offline');
            }
        }
        
        // 测试用户ID持久化
        function testUserIdPersistence() {
            try {
                log('🧪 测试用户ID持久化...');
                
                const currentId = headerHandlers.getUserId();
                const storedId = localStorage.getItem('chatAppUserId');
                
                if (currentId === storedId) {
                    log('✅ 用户ID持久化正常');
                } else {
                    log(`⚠️ 用户ID持久化异常: 当前=${currentId}, 存储=${storedId}`);
                }
                
            } catch (error) {
                log(`❌ 测试持久化失败: ${error.message}`);
            }
        }
        
        // 模拟用户ID变更
        function simulateUserIdChange() {
            try {
                log('🧪 模拟用户ID变更...');
                const timestamp = Date.now();
                const simulatedId = `test_${timestamp}`;
                headerHandlers.setCustomUserId(simulatedId);
                log(`🔄 模拟用户ID变更完成: ${simulatedId}`);
            } catch (error) {
                log(`❌ 模拟用户ID变更失败: ${error.message}`);
            }
        }
        
        // 清除用户数据
        function clearUserData() {
            if (!confirm('确定要清除所有用户数据吗？这将删除用户ID和相关设置。')) {
                return;
            }
            
            try {
                headerHandlers.clearUserData();
                log('🗑️ 用户数据已清除');
                setTimeout(() => {
                    location.reload();
                }, 1000);
            } catch (error) {
                log(`❌ 清除用户数据失败: ${error.message}`);
            }
        }
        
        // 更新同步状态指示器
        function updateSyncStatus(status) {
            const indicator = document.getElementById('sync-status');
            indicator.className = `status-indicator ${status}`;
        }
        
        // 清空日志
        function clearLog() {
            document.getElementById('log-output').textContent = '';
        }
        
        // 日志输出函数
        function log(message) {
            const logOutput = document.getElementById('log-output');
            const timestamp = new Date().toLocaleTimeString();
            logOutput.textContent += `[${timestamp}] ${message}\n`;
            logOutput.scrollTop = logOutput.scrollHeight;
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>
</html>
